import {Component, ElementRef, OnDestroy, OnInit} from "@angular/core";
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import {FetchService} from "../../../core/net/fetch.service";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {DomSanitizer, SafeResourceUrl} from "@angular/platform-browser";
import {Rect, Topology} from "topology-core";
import {Options} from "topology-core/options";
import * as _ from "lodash";
import { DpReportOverviewComponent } from '../dp-report-overview/dp-report-overview.component';

@Component({
  selector: 'app-dispatch-qs',
  templateUrl: './dispatch-qs.component.html',
  styleUrls: ['../dispatch-common.scss', './dispatch-qs.component.scss']
})
export class DispatchQsComponent implements OnInit, OnDestroy {
  applyModalShow = false;
  applyForm: FormGroup;

  replyForm: FormGroup;
  recordModalShow = false;
  dutyRecordModalShow = false;

  jqsbModalShow = false;
  jqsbForm: FormGroup;
  officeOption;

  // 概化图
  canvas: Topology;
  canvasOptions: Options = {};
  rect: Rect;
  hoverItem = {
    top: '0px',
    left: '0px',
    alertLevel: '-',
    waterLevel: '-',
    limitTraffic: '-',
    flow: '-'
  };
  infoShow = false;

  jskllModalShow = false;
  qsJskllSrc: SafeResourceUrl;
  glcData;

    canalList = [];
    defaultCanal;
    barOpt: any = {
        color: ['#5793f3', '#d14a61', '#675bba'],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            }
        },
        legend: {
            data: [],
            bottom: 0
        },
        grid: {
            top: "12%",
            bottom: "8%",
            left: "6%",
            right: "4%",
            containLabel: true
        },
        xAxis: {
            type: "category",
            data: []
        },
        yAxis: [
            {
                type: 'value',
                name: '流量(m³/s)',
                position: 'right',
                axisLine: {
                    lineStyle: {
                        color: '#d14a61'
                    }
                }
            },
            {
                type: 'value',
                name: '水位（m）',
                position: 'left',
                axisLine: {
                    lineStyle: {
                        color: '#5793f3'
                    }
                }
            }
        ],
        series: [
            {
                name: '水位',
                type: 'bar'
            },
            {
                name: '流量',
                type: 'line',
                yAxisIndex: 1
            }
        ]
    };
    barOptChange: any = {};
  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private fetchService: FetchService,
    private sanitizer: DomSanitizer,
    private modalService: NzModalService,
    private el: ElementRef
  ) {
    this.applyForm = this.fb.group({
      id: [null],
      addType: [1],
      addNum: [0],
      startType: [1],
      applyLargeUnit: [0],
      applySmallUnit: [0],
      appliedFlow: [],
      applyTime: [null, Validators.required],
      remark: [null]
    });

    this.replyForm = this.fb.group({
      id: [null],
      addType: [1],
      addNum: [0],
      appliedFlow: [],
      applyTime: [null],
      remark: [null]
    });

    this.jqsbForm = this.fb.group({
      title: [''],
      // objId: [''],
      info: ['']
    });

    this.canalList = [
          {
              label: '渠道名称',
              value: 1
          }
      ];
    this.defaultCanal = this.canalList[0].value;
  }

  ngOnInit(): void {
    window.addEventListener('resize', this.debounce(() => {
      this.onResize();
    }, 500));
    // this.getApplyObject();
    // this.getReplyObject();
    this.getMapData2();
    this.getOfficeOption();
    this.queryJskll();
    this.canalSelectionChange();
  }

  ngOnDestroy(): void {
    // this.canvas.destroy();
  }

  // 防抖函数
  debounce(func, wait?, immediate?): any {
    let timeout;
    return function() {
      const context = this;
      const args = arguments;
      const later = () => {
        timeout = null;
        if (!immediate) {
          func.apply(context, args);
        }
      };
      const callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) {
        func.apply(context, args);
      }
    };
  }

  // 窗口变化
  onResize() {
    console.log('windonw is resize');
    const h = this.el.nativeElement.querySelector('.canvas-wrap').getBoundingClientRect().height;
    const w = this.el.nativeElement.querySelector('.canvas-wrap').getBoundingClientRect().width; // 设置画布
    this.rect = this.canvas.getRect();
    if (this.rect.width / this.rect.height > w / h) {
      this.canvas.scale(w / this.rect.width * 0.9);
    } else {
      this.canvas.scale(h / this.rect.height * 0.97);
    }
    this.canvas.translate(w / 2 - this.rect.center.x, h / 2 - this.rect.center.y);
  }

  getOfficeOption(): void {
    this.fetchService.post<any>('schedule/actualDispatchMonData/list', {}).subscribe(res => {
      this.officeOption = res;
    });
  }

  getMapData2(): void {
    this.fetchService.post<any>('schedule/actualDispatchMonData/data', {manageId: 6}).subscribe(r => {
      this.glcData = r;
      this.fetchService.get<any>('assets/data/qsnew/1.json').subscribe(res => {
        const pens = res.pens;
        // 数据处理
        this.glcData.map(feature => {
          for (const pen of pens) {
            // 修改闸门颜色
            if (pen.data.cid == feature.objId) {
              pen.image = '/yjq_web/assets/images/ght/newicons/' + feature.objType + feature.status + '.png';
            }
            // 修改q
            if (pen.data.cid == `${feature.objId}q`) {
              pen.text = feature.flow ?  feature.flow + 'm³/s' : '-m³/s';
            }
            // 修改h
            if (pen.data.cid == `${feature.objId}h`) {
              pen.text = feature.waterLevel ? feature.waterLevel + 'm' : '-m';
            }
          }
        });

        if (this.canvas) {
          // 重置画布数据
          this.canvas.open({
            id: '',
            version: '',
            name: 'new空白文件',
            desc: '',
            image: '',
            userId: '',
            class: '',
            component: false,
            shared: false
          });
        } else {
          // 创建画布
          this.canvasOptions.on = this.onMouseEvent;
          this.canvas = new Topology('topology-canvas', this.canvasOptions);
        }
        this.canvas.open(res);

        // 设置画布
        this.onResize();
      });
    });
  }

  // 概化图元素事件
  onMouseEvent = (event: string, node: any) => {
    if (event === 'moveInNode') {
      if (node.data != '' && (['ZZ', 'ZQ', 'gate', 'gate_out'].indexOf(node.data.type) > -1)) {
        console.log(event, node);
        this.infoShow = true;
        const yArr = [node.rotatedAnchors[0].y, node.rotatedAnchors[1].y, node.rotatedAnchors[2].y, node.rotatedAnchors[3].y];
        const featureH = _.max(yArr) - _.min(yArr);
        console.log(featureH);
        this.hoverItem.top = (node.rect.center.y - 120 - featureH / 2 + 10) + 'px';
        this.hoverItem.left = (node.rect.center.x - 76) + 'px';

        const nodeId = node.data.cid;
        this.glcData.map(item => {
          if (item.objId == nodeId) {
            this.hoverItem.alertLevel = item.alertLevel || '-';
            this.hoverItem.flow = item.flow || '-';
            this.hoverItem.limitTraffic = item.limitTraffic || '-';
            this.hoverItem.waterLevel = item.waterLevel || '-';
          }
        });
      }
    }
    if (event === 'moveOutNode') {
      this.infoShow = false;
      this.hoverItem.alertLevel = '-';
      this.hoverItem.flow = '-';
      this.hoverItem.limitTraffic = '-';
      this.hoverItem.waterLevel = '-';
    }
    if (event === 'node') {
      // alert(node.data.name + '被点击了');
    }
  }

  openRecordModal(): void {
    this.recordModalShow = true;
  }

  onApplyCancel(): void {
    this.applyModalShow = false;
  }

  openApplyModal(): void {
    this.applyModalShow = true;
  }

  openDutyRecordModal(): void {
    this.dutyRecordModalShow = true;
  }

  openJqsbModal() {
    this.jqsbModalShow = true;
    this.jqsbForm.reset();
  }

  onJqsbConfirm() {
    this.modalService.confirm({
      nzTitle: '确认上报该警情？',
      nzContent: '',
      nzOnOk: () => {
        this.fetchService.post('schedule/actualDispatchWarning/add', this.jqsbForm.value).subscribe(res => {
          this.message.success('操作成功！');
          this.jqsbModalShow = false;
        });
      }
    });
  }

  queryJskll(): void {
    const year = new Date().getFullYear();
    const month = new Date().getMonth() + 1;
    const token = localStorage.token;
    const serverUrl = (window as any).environment.reportUrl;
    const link = `${serverUrl}preview?_u=wrs:骨干排水沟.ureport.xml&_t=3,6&year=${year}&month=${month}&token=${token}`;
    this.qsJskllSrc = this.sanitizer.bypassSecurityTrustResourceUrl(link);
  }
    /**
     * 打开报送一览弹窗
     */
    openReportModal(): void {
        const modal = this.modalService.create({
            nzTitle: '报送一览',
            nzContent: DpReportOverviewComponent,
            nzComponentParams: {
                mngType: 1,
            },
            nzFooter: null,
            nzWidth: '1050',
            nzClassName: 'dispatch-modal',
            nzOnCancel: () => {
                modal.destroy();
            }
        });
    }

    canalSelectionChange(): void {
        this.fetchService.post<any>("base/wrsBrwaterCannal/listLast", {
            pageSize: 1000
        }).subscribe(res => {
            this.barOptChange = {
                xAxis: {
                    data: res['list'].map(item => {
                        return item['stadiaName'];
                    }),
                    axisLabel: {
                        interval: 0
                    }
                },
                series: [
                    {
                        name: '水位',
                        type: 'bar',
                        data: res['list'].map(item => {
                            return item['waterHeight'];
                        })
                    },
                    {
                        name: '流量',
                        type: 'line',
                        yAxisIndex: 1,
                        data: res['list'].map(item => {
                            return item['flux'];
                        })
                    }
                ]
            };
        });
    }
}
